﻿using e_commerce.BLL.Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace e_commerce.BLL.Services.Client
{
    public class DeliveryManager : IDisposable
    {
        private readonly commerceDbContext _dbContext;
        public DeliveryManager()
        {
            _dbContext = new commerceDbContext();
        }

        public IEnumerable<DeliveryInfo> GetDeliveryByClientId(int clientId)
        {
            return _dbContext.DeliveryInfo.Where(d => d.ClientId == clientId);
        }

        public DeliveryInfo GetDeliveryById(int deliverId)
        {
            return _dbContext.DeliveryInfo.Single(d => d.Id == deliverId);
        }
        public bool CheckDeliverCount(int clientId)
        {
            var list = GetDeliveryByClientId(clientId);
            return list.Count() <= 10 ? true : false;
        }

        public void AddNewDeliveryInfo(DeliveryInfo de)
        {
            var count = GetDeliveryByClientId(de.ClientId).Count();
            if (count + 1 >= 10)
            {
                throw new Exception("地址数量超限");
            }
            _dbContext.DeliveryInfo.Add(de);
            SaveChange();
        }

        public void DeleteDelivery(int id)
        {
            var d = GetDeliveryById(id);
            _dbContext.DeliveryInfo.Remove(d);
            SaveChange();
        }

        public void SetDefaultDelivery(int clientId, int deliveryId)
        {
            var deliverys = _dbContext.DeliveryInfo.Where(d => d.ClientId == clientId && !d.IsDelete);
            bool flag = false;
            foreach(var de in deliverys)
            {
                if(de.Id == deliveryId)
                {
                    de.IsDefault = true;
                    flag = true;
                }
                else
                {
                    de.IsDefault = false;
                }
            }
            if(flag == false)
            {
                throw new Exception("The delivery not found");
            }
            SaveChange();
        }

        public void SaveChange()
        {
            _dbContext.SaveChanges();
        }

        public void Dispose()
        {
            _dbContext.Dispose();
        }
    }
}
